package com.bnz.search.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bnz.search.dao.ItemDao;
import com.bnz.search.entity.ItemEntity;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;

import java.util.List;
import java.util.Map;


@SpringBootTest
public class EsUtil {

	@Autowired
	private ElasticsearchRestTemplate elasticsearchRestTemplate;
	@Autowired
	private ItemDao itemDao;
	/**
	 * 1、从数据库中将tb_item表中的数据导入到es中
	 */
	@Test
	public void test01(){
		//1.1 查询数据库,查询出所有状态为1，即为审核通过的sku商品列表
		List<ItemEntity> itemEntities = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("status", 1));
		//1.2 处理动态字段spec查询
		for (ItemEntity item : itemEntities) {
			String spec = item.getSpec();
			Map map = JSON.parseObject(spec, Map.class);
			item.setSpecMap(map);
		}
		//1.3 导入数据到索引库中
		elasticsearchRestTemplate.save(itemEntities);
		System.out.println("存入索引库成功！");
	}

	@Test
	public void test02(){
		NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
		NativeSearchQuery query = builder.withQuery(QueryBuilders.matchQuery("goodsId", "149187842867985")).build();
		elasticsearchRestTemplate.delete(query,ItemEntity.class, IndexCoordinates.of("item"));

	}
}
